<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2019/3/13
 * Time: 0:32
 */
namespace app\index\controller;

use app\admin\model\Lottery;
use app\index\model\LotteryLog;

class Prize extends Base {

    public function __construct(){
        parent::__construct();
    }

    /**
     * 获取活动抽奖
     * @param int $id
     * @param int $mc_id
     * @param int $limit
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_prize($id=0,$mc_id=0,$limit=8){
        if(!$id){
            return $this->__json(1,'缺少参数');
        }
        $prize = new Lottery();
        $list = $prize->getListByAid($id,$limit,'id,prize,num');
        $log = new LotteryLog();
        $result = $log->is_check($mc_id,self::$uid,$out);
        if(!$list){
            $this->__json(2,$out);
        }
        $this->__json(0,'done',['list'=>$list,'is_prize'=>$result]);
    }

    /**
     * 抽奖
     * @param int $id
     * @param int $mc_id
     * @param int $limit
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function start($id=0,$mc_id=0,$limit=8){
        if(!$id || !$mc_id){
            return $this->__json(1,'缺少参数');
        }
        $log = new LotteryLog();
        $result = $log->is_check($mc_id,self::$uid);
        if($result){
            return $this->__json(2,'您已今日已参与该商户的抽奖活动，请明日再来');
        }
        $pize = new Lottery();
        $prize_arr = $pize->getChangeListByAid($id,self::$uid,$limit,'id,prize,num');
        if(!$prize_arr){
            return $this->__json(2,'抽奖活动已结束');
        }
        $prize_arr = $prize_arr->toArray();
        $_prize = [];
        $arr = [];
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['v'];
            $_prize[$val['id']] = $val;
        }
        if(!$arr){
            return $this->__json(2,'抽奖活动已结束');
        }
        $rid = get_rand($arr); //根据概率获取奖项id
        $res['yes'] = [
            'id'=>$_prize[$rid]['id'],
            'prize'=>$_prize[$rid]['prize']
        ]; //中奖项
        //将中奖项从数组中剔除，剩下未中奖项，如果是数据库验证，这里可以省掉
        //unset($prize_arr[$rid-1]);
        shuffle($_prize); //打乱数组顺序
        for($i=0;$i<count($_prize);$i++){
            $pr[] = [
                'id'=>$_prize[$i]['id'],
                'prize'=>$_prize[$i]['prize']
            ];
        }
        $res['no'] = $pr;
        if($res['yes']){
            $prize = new Lottery();
            $result1 = $prize->updateStore($res['yes']['id'],$id,self::$uid,$mc_id,$out);
            if($result1){
                $res['yes']['lid'] = $result1;
                return $this->__json(0,'done', $res);
            }else{
                return $this->__json(1,$out);
            }
        }
    }
}